Form validation is the process of checking that the data entered by a user into a web form is correct,
complete, and secure before it is processed.
It is crucial for:
User Experience (UX): Giving instant feedback to users if they make a mistake.
Data Integrity: Ensuring you get the right format of data (e.g., a valid email).
Security: Preventing malicious data from being sent to your server.
2. Types of Form Validation
There are two main types of validation:
Client-Side Validation: Happens in the browser (using HTML5 attributes or JavaScript) before data
is sent to the server. It provides immediate feedback.
Server-Side Validation: Happens on the server after data is sent. This is the last line of
defense and is mandatory for security.
3. HTML5 Built-in Validation
HTML5 provides built-in attributes to validate data without writing any JavaScript.
<input type="text" required> <!-- Field cannot be empty -->
<input type="email" required> <!-- Must be an email format -->
<input type="number" min="1" max="10"> <!-- Number between 1 and 10 -->
<input type="text" minlength="3"> <!-- Minimum 3 characters -->
4. JavaScript Validation Logic
While HTML5 is great, JavaScript gives you full control over validation rules and custom error messages.
The general logic is:
Listen for the form's submit event.
Prevent the default submission using e.preventDefault().
Check the values of input fields against your rules.
If invalid, show an error message and stop. If valid, proceed.
5. Example: Custom Form Validation
Try submitting the form empty or with invalid data to see the validation in action.
let form = document.getElementById("regForm");
form.addEventListener("submit", function(e) {
e.preventDefault(); // Stop form submission
if(validate()) {
document.getElementById("successMsg").innerText =
"Form Submitted Successfully!";
}
});
function validate() {
let valid = true;
let name = document.getElementById("name").value;
let email = document.getElementById("email").value;
let password = document.getElementById("password").value;
// Name Validation
if(name.trim() === "") {
document.getElementById("nameError").innerText = "Name required";
valid = false;
}
// Email Validation
if(email.trim() === "") {
document.getElementById("emailError").innerText = "Email required";
valid = false;
}
// Password Validation
if(password.length < 6) {
document.getElementById("passError").innerText =
"Minimum 6 characters";
valid = false;
}
return valid;
}
6. Validation Using Regular Expressions (Regex)
Regular Expressions are patterns used to match character combinations in strings. They are powerful for
validating complex formats like emails, phone numbers, or passwords.
// Simple Email Regex Pattern
let emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
let email = "test@example.com";
// .test() returns true if the string matches the pattern
if(!emailPattern.test(email)) {
emailError.innerText = "Invalid email format";
}
Output will appear here...
7. Comparison: Validation Methods
Validation Type
Speed
Security
Use Case
HTML5
Fast
Low
Basic forms
JavaScript
Fast
Medium
Custom rules
Server-Side
Slow
High
Final validation
✅ Best Practice: Always use both client-side (for UX) and server-side (for security) validation
together. Never rely solely on JavaScript validation as it can be disabled by the user.
Practice Questions
Test your understanding of JavaScript Form Validation.
Easy
Q1: Prevent empty form submission using HTML5.
Create a text input field for a username.
Use an HTML5 attribute to prevent the form from submitting if the field is empty.
You can use the required attribute directly on your input elements. HTML5 will automatically show a warning and block submission if the field is left empty.
<input type="text" name="username" required>
Easy
Q2: Prevent default form submission.
Assume you have a form with the ID myForm.
Attach an event listener for the submit event.
Write the JavaScript method to stop the page from reloading.
You need to call the preventDefault() method on the event object passed to your submit event listener.
let form = document.getElementById("myForm");
form.addEventListener('submit', function(e) {
e.preventDefault();
});
Medium
Q3: Validate a numeric input field.
Retrieve the value from an input field with the ID age.
Convert the value to a Number.
Log an error message if the age is less than 18.
Retrieve the value from the element, optionally convert it to a Number, and use an if statement to evaluate the condition.
let age = document.getElementById('age').value;
if (Number(age) < 18) {
document.write("You must be at least 18.");
}
Medium
Q4: Validate a password using Regular Expressions (Regex).
Write a regex pattern for a password.
Ensure it is at least 8 characters long.
Ensure it contains at least one number.
Test the pattern against the string "pass1234" and log the result.
You can use a positive lookahead (?=.*\d) to ensure a digit exists, and .{8,} to enforce the minimum length of 8 characters.
let regex = /^(?=.*\d).{8,}$/;
document.write(regex.test("pass1234")); // true
Hard
Q5: Create a custom email validation script.
Retrieve the value of an email input field.
Check if it contains the "@" symbol and ends with ".com".
If invalid, display an error message in a span with the ID emailError.
Access the input's value, perform checks using includes() and endsWith(), and update the innerText of the error span.
let email = document.getElementById('email').value;
let errorSpan = document.getElementById('emailError');
if (!email.includes('@') || !email.endsWith('.com')) {
errorSpan.innerText = 'Invalid email format';
return false;
}